//
//  TL_LoginDetailViewController.m
//  WXReader
//
//  Created by LL on 2020/9/7.
//  Copyright © 2020 Andrew. All rights reserved.
//

#import "TL_LoginDetailViewController.h"

#import "UIView+LayoutCallback.h"
#import "TL_SendCodeButton.h"

#import "NSObject+Observer.h"

@interface TL_LoginDetailViewController ()

@property (nonatomic, strong) UITextField *accountTextField;

@property (nonatomic, strong) UITextField *codeTextField;

@property (nonatomic, strong) TL_SendCodeButton *sendCodeButton;

@property (nonatomic, strong) UIButton *loginButton;

@end

@implementation TL_LoginDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialize];
    [self createSubviews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setStatusBarDefaultStyle];
}

#pragma mark - 初始化
- (void)initialize {
    [self.navigationBar setNavigationBarTitle:WXLocalizedString(@"邮箱登录")];
}

#pragma mark - UI
- (void)createSubviews {
    UIScrollView *scrollView = [TL_UIFactory scrollView];
    scrollView.backgroundColor = kWhiteColor;
    scrollView.contentInset = UIEdgeInsetsMake(0, 0, PUB_TABBAR_OFFSET, 0);
    [self.view addSubview:scrollView];
    
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navigationBar.mas_bottom);
        make.left.right.bottom.mas_equalTo(self.view);
    }];
    
    MK_WEAK_SELF
    [scrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf.view endEditing:YES];
    }]];
    
    self.accountTextField = [TL_UIFactory textFieldWithBackgroundColor:kWhiteColor placeholder:WXLocalizedString(@"邮箱") textColor:kBlackColor font:SYSTEM_FONT(16) delegate:nil isNumber:NO];
    [self.accountTextField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.accountTextField.keyboardType = UIKeyboardTypeEmailAddress;
    self.accountTextField.frameBlock = ^(UIView * _Nonnull view) {
        [view addBorderLineWithBorderWidth:kCellLineHeight borderColor:kGrayLineColor cornerRadius:0 borderType:UIBorderSideTypeBottom];
    };
//    self.accountTextField.text = @"123457@111.22";
    [scrollView addSubview:self.accountTextField];

    [self.accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(2 * kMargin);
        make.height.mas_equalTo(kGeometricWidth(SCREEN_WIDTH - 4 * kMargin, 61.0, 334.0));
        make.width.mas_equalTo(kScreenWidth-kMargin*4);
    }];

    self.codeTextField = [TL_UIFactory textFieldWithBackgroundColor:self.accountTextField.backgroundColor placeholder:WXLocalizedString(@"验证码") textColor:self.accountTextField.textColor font:self.accountTextField.font delegate:nil isNumber:YES];
    [self.codeTextField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
//    self.codeTextField.text = @"123456";
    [scrollView addSubview:self.codeTextField];

    [self.codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.equalTo(self.accountTextField);
        make.top.equalTo(self.accountTextField.mas_bottom).offset(kMargin);
    }];

    self.sendCodeButton = [[TL_SendCodeButton alloc] initWithFrame:CGRectZero identify:@"login_timer"];
    self.sendCodeButton.enabled = NO;
    [self.sendCodeButton.titleLabel setFont:kMainFont];
    self.sendCodeButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.sendCodeButton setTitleColor:RGB(231, 85, 79) forState:UIControlStateNormal];
    [self.sendCodeButton setTitleColor:RGB(199, 199, 205) forState:UIControlStateDisabled];
    [self.sendCodeButton addTarget:self action:@selector(sendCodeEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.sendCodeButton.frameBlock = ^(UIButton * _Nonnull button) {
        [button addBorderLineWithBorderWidth:kCellLineHeight borderColor:kGrayLineColor cornerRadius:0 borderType:UIBorderSideTypeLeft];
    };
    [scrollView addSubview:self.sendCodeButton];

    [self.sendCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.accountTextField);
        make.centerY.equalTo(self.codeTextField);
        if (self.sendCodeButton.countdownState) {
            make.width.mas_equalTo(160);
        } else {
            make.width.mas_equalTo(self.sendCodeButton.intrinsicContentSize.width + kMargin);
        }
        make.height.mas_equalTo(self.sendCodeButton.titleLabel.intrinsicContentSize.height);
    }];

    [self.codeTextField mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.sendCodeButton.mas_left).offset(-kQuarterMargin);
    }];

    UIView *codeLineView = [TL_UIFactory view];
    codeLineView.backgroundColor = kGrayLineColor;
    [scrollView addSubview:codeLineView];

    [codeLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.accountTextField);
        make.bottom.mas_equalTo(self.codeTextField);
        make.height.mas_equalTo(kCellLineHeight);
    }];

    self.loginButton = [TL_UIFactory buttonWithType:UIButtonTypeCustom backgroundColor:RGB(229, 230, 232) font:SYSTEM_FONT(15) textColor:kWhiteColor target:self action:@selector(loginEvent:)];
    [self.loginButton setTitleColor:kGrayTextColor forState:UIControlStateDisabled];
    [self.loginButton setTitle:WXLocalizedString(@"登录") forState:UIControlStateNormal];
    [self.loginButton addObserver:KEY_PATH(self.loginButton, enabled) complete:^(UIButton * _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
        obj.backgroundColor = [newVal boolValue] ? RGB(231, 85, 79) : RGB(229, 230, 232);
    }];
    self.loginButton.enabled = NO;
    self.loginButton.frameBlock = ^(UIButton * _Nonnull button) {
        button.layer.cornerRadius = (CGRectGetWidth(button.bounds) + CGRectGetHeight(button.bounds)) * 0.058;
    };
    [scrollView addSubview:self.loginButton];

    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.accountTextField);
        make.top.equalTo(codeLineView.mas_bottom).offset(60);
        make.height.equalTo(self.loginButton.mas_width).multipliedBy(44.0 / 334.0);
        make.bottom.mas_equalTo(scrollView).offset(-2*kMargin);
    }];
}

#pragma mark - Event
- (void)sendCodeEvent:(TL_SendCodeButton *)button {
    if (![[NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"] evaluateWithObject:self.accountTextField.text]) {
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"格式不正确")];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.accountTextField.text forKey:@"email"];
    button.enabled = NO;

    MK_WEAK_SELF
    
    [APIManager sendPostRequest:[APIURLManager sendEmailValidCode] parameters:params model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"验证码已发送")];
            [weakSelf.codeTextField becomeFirstResponder];
            [button startTiming];
        } else {
            button.enabled = YES;
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
            button.enabled = YES;
            [TL_TopAlertManager showAlertWithError:error defaultText:WXLocalizedString(@"发送失败")];
    }];
    
}

/// 邮箱登录
- (void)loginEvent:(UIButton *)loginButton {
    self.view.userInteractionEnabled = NO;

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.accountTextField.text forKey:@"email"];
    [params setObject:self.codeTextField.text forKey:@"verificationCode"];
    
    MK_WEAK_SELF
    
    [APIManager sendPostRequest:[APIURLManager emailLogin] parameters:params model:TL_UserInfoModel.class success:^(BOOL success, TL_UserInfoModel *  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            
//            [TL_UserInfoModel modelWithDictionary:requestModel.data[@"userInfo"]];
//            TL_UserInfoModel * u_model = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];
            
            TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];
            NSString *token = requestModel.data[@"token"];
            
            [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"userToken"];
            
            NSLog(@"user token: %@",token);
            
            NSDictionary *userDataDict = [usermodel mj_keyValues];
            
            [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
            
            !weakSelf.closeBlock ?: weakSelf.closeBlock();
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"登录失败")];
            weakSelf.view.userInteractionEnabled = YES;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"登录失败")];
        weakSelf.view.userInteractionEnabled = YES;
    }];
    
}

- (void)textDidChange:(UITextField *)textField {
    if (!self.sendCodeButton.countdownState) {
        self.sendCodeButton.enabled = (self.accountTextField.text.length > 0);
    }
    
    self.loginButton.enabled = (self.accountTextField.text.length > 0 && self.codeTextField.text.length > 0);
}

/// 游客登录
- (void)touristsLogin {
    MK_WEAK_SELF
    
    [APIManager sendPostRequest:[APIURLManager Tourists_Login] parameters:@{@"udid":[TL_UtilsHelper getUDID]} model:TL_UserInfoModel.class success:^(BOOL success, TL_UserInfoModel*  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            if (responseData.is_new) {
//                [TL_AnalyticsManager logEvent:@"registration" params:@{}];
            }
            !weakSelf.closeBlock ?: weakSelf.closeBlock();
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [TL_TopAlertManager showAlertWithError:error defaultText:WXLocalizedString(@"登录失败")];
    }];
}

@end
